<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>人脸质量检测 - 调试工具</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Microsoft YaHei', sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            padding: 20px;
        }
        
        .container {
            max-width: 1200px;
            margin: 0 auto;
            background: white;
            border-radius: 20px;
            box-shadow: 0 20px 60px rgba(0, 0, 0, 0.3);
            overflow: hidden;
        }
        
        .header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 30px;
            text-align: center;
        }
        
        .header h1 {
            font-size: 32px;
            margin-bottom: 10px;
        }
        
        .header p {
            font-size: 16px;
            opacity: 0.9;
        }
        
        .content {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 30px;
            padding: 30px;
        }
        
        .section {
            background: #f8f9fa;
            padding: 25px;
            border-radius: 15px;
            border: 2px solid #e9ecef;
        }
        
        .section h2 {
            color: #667eea;
            margin-bottom: 20px;
            font-size: 20px;
            display: flex;
            align-items: center;
            gap: 10px;
        }
        
        .upload-area {
            border: 3px dashed #dee2e6;
            border-radius: 10px;
            padding: 40px;
            text-align: center;
            cursor: pointer;
            transition: all 0.3s;
            background: white;
        }
        
        .upload-area:hover {
            border-color: #667eea;
            background: #f8f9ff;
        }
        
        .upload-area.dragover {
            border-color: #667eea;
            background: #f0f2ff;
            transform: scale(1.02);
        }
        
        .upload-icon {
            font-size: 48px;
            margin-bottom: 15px;
        }
        
        input[type="file"] {
            display: none;
        }
        
        .form-group {
            margin-bottom: 20px;
        }
        
        .form-group label {
            display: block;
            margin-bottom: 8px;
            color: #495057;
            font-weight: 500;
        }
        
        .form-group input,
        .form-group select {
            width: 100%;
            padding: 12px;
            border: 2px solid #e9ecef;
            border-radius: 8px;
            font-size: 14px;
            transition: border-color 0.3s;
        }
        
        .form-group input:focus,
        .form-group select:focus {
            outline: none;
            border-color: #667eea;
        }
        
        .btn {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border: none;
            padding: 15px 30px;
            border-radius: 8px;
            font-size: 16px;
            font-weight: 600;
            cursor: pointer;
            width: 100%;
            transition: transform 0.2s, box-shadow 0.2s;
        }
        
        .btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 10px 20px rgba(102, 126, 234, 0.3);
        }
        
        .btn:active {
            transform: translateY(0);
        }
        
        .btn:disabled {
            opacity: 0.6;
            cursor: not-allowed;
        }
        
        .result {
            margin-top: 20px;
            padding: 20px;
            border-radius: 10px;
            display: none;
        }
        
        .result.success {
            background: #d4edda;
            border: 2px solid #28a745;
            color: #155724;
        }
        
        .result.error {
            background: #f8d7da;
            border: 2px solid #dc3545;
            color: #721c24;
        }
        
        .result h3 {
            margin-bottom: 15px;
            font-size: 18px;
        }
        
        .result-details {
            background: white;
            padding: 15px;
            border-radius: 8px;
            margin-top: 10px;
        }
        
        .result-details pre {
            margin: 0;
            white-space: pre-wrap;
            word-wrap: break-word;
            font-size: 13px;
            font-family: 'Courier New', monospace;
        }
        
        .preview-image {
            max-width: 100%;
            max-height: 400px;
            border-radius: 10px;
            margin-top: 15px;
            box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
        }
        
        .spinner {
            border: 3px solid #f3f3f3;
            border-top: 3px solid #667eea;
            border-radius: 50%;
            width: 30px;
            height: 30px;
            animation: spin 1s linear infinite;
            margin: 20px auto;
            display: none;
        }
        
        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }
        
        .badge {
            display: inline-block;
            padding: 5px 12px;
            border-radius: 20px;
            font-size: 12px;
            font-weight: 600;
            margin: 5px 5px 5px 0;
        }
        
        .badge-success {
            background: #28a745;
            color: white;
        }
        
        .badge-danger {
            background: #dc3545;
            color: white;
        }
        
        .badge-info {
            background: #17a2b8;
            color: white;
        }
        
        .stats-grid {
            display: grid;
            grid-template-columns: repeat(2, 1fr);
            gap: 10px;
            margin-top: 10px;
        }
        
        .stat-item {
            background: #f8f9fa;
            padding: 12px;
            border-radius: 8px;
            text-align: center;
        }
        
        .stat-label {
            font-size: 12px;
            color: #6c757d;
            margin-bottom: 5px;
        }
        
        .stat-value {
            font-size: 18px;
            font-weight: 700;
            color: #667eea;
        }
        
        @media (max-width: 768px) {
            .content {
                grid-template-columns: 1fr;
            }
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1>🔍 人脸质量检测</h1>
            <p>基于 InsightFace 的智能人脸质量评估工具</p>
        </div>
        
        <div class="content">
            <!-- 左侧：上传区域 -->
            <div class="section">
                <h2>📤 上传检测</h2>
                
                <div class="upload-area" id="uploadArea">
                    <div class="upload-icon">📷</div>
                    <p style="font-size: 16px; color: #495057; margin-bottom: 10px;">
                        <strong>点击或拖拽上传图片</strong>
                    </p>
                    <p style="font-size: 13px; color: #6c757d;">
                        支持 JPG、PNG、BMP 格式，最大 10MB
                    </p>
                    <input type="file" id="fileInput" accept="image/*">
                </div>
                
                <div style="margin: 20px 0; text-align: center; color: #6c757d;">
                    <span>或</span>
                </div>
                
                <div class="form-group">
                    <label>🔗 从URL加载图片</label>
                    <input type="text" id="imageUrl" placeholder="https://example.com/image.jpg">
                </div>
                
                <h3 style="margin: 25px 0 15px 0; color: #495057; font-size: 16px;">⚙️ 检测参数</h3>
                
                <div class="form-group">
                    <label>最小人脸尺寸（像素）</label>
                    <input type="number" id="minFaceSize" placeholder="100" value="100">
                </div>
                
                <div class="form-group">
                    <label>最大姿态角度（度）</label>
                    <input type="number" id="maxAngle" placeholder="15" value="15" step="0.1">
                </div>
                
                <div class="form-group">
                    <label>清晰度阈值</label>
                    <input type="number" id="blurThreshold" placeholder="60" value="60" step="0.1">
                </div>
                
                <button class="btn" id="detectBtn" disabled>
                    🚀 开始检测
                </button>
                
                <div class="spinner" id="spinner"></div>
            </div>
            
            <!-- 右侧：结果显示 -->
            <div class="section">
                <h2>📊 检测结果</h2>
                
                <div id="previewContainer" style="text-align: center;">
                    <p style="color: #6c757d; padding: 40px 0;">
                        等待上传图片...
                    </p>
                </div>
                
                <div class="result" id="resultBox">
                    <h3 id="resultTitle"></h3>
                    <div id="resultMessage"></div>
                    <div class="result-details" id="resultDetails" style="display: none;">
                        <pre id="resultJson"></pre>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script>
        const uploadArea = document.getElementById('uploadArea');
        const fileInput = document.getElementById('fileInput');
        const imageUrl = document.getElementById('imageUrl');
        const detectBtn = document.getElementById('detectBtn');
        const spinner = document.getElementById('spinner');
        const resultBox = document.getElementById('resultBox');
        const resultTitle = document.getElementById('resultTitle');
        const resultMessage = document.getElementById('resultMessage');
        const resultDetails = document.getElementById('resultDetails');
        const resultJson = document.getElementById('resultJson');
        const previewContainer = document.getElementById('previewContainer');
        
        let currentFile = null;
        
        // 点击上传区域
        uploadArea.addEventListener('click', () => fileInput.click());
        
        // 文件选择
        fileInput.addEventListener('change', handleFileSelect);
        
        // 拖拽上传
        uploadArea.addEventListener('dragover', (e) => {
            e.preventDefault();
            uploadArea.classList.add('dragover');
        });
        
        uploadArea.addEventListener('dragleave', () => {
            uploadArea.classList.remove('dragover');
        });
        
        uploadArea.addEventListener('drop', (e) => {
            e.preventDefault();
            uploadArea.classList.remove('dragover');
            
            const files = e.dataTransfer.files;
            if (files.length > 0) {
                fileInput.files = files;
                handleFileSelect();
            }
        });
        
        // 处理文件选择
        function handleFileSelect() {
            const file = fileInput.files[0];
            if (file) {
                currentFile = file;
                detectBtn.disabled = false;
                previewImage(file);
                resultBox.style.display = 'none';
            }
        }
        
        // 预览图片
        function previewImage(file) {
            const reader = new FileReader();
            reader.onload = (e) => {
                previewContainer.innerHTML = `
                    <img src="${e.target.result}" class="preview-image" alt="预览">
                    <p style="margin-top: 10px; color: #495057;">
                        <strong>${file.name}</strong> (${(file.size / 1024).toFixed(1)} KB)
                    </p>
                `;
            };
            reader.readAsDataURL(file);
        }
        
        // 检测按钮
        detectBtn.addEventListener('click', async () => {
            const url = imageUrl.value.trim();
            
            if (currentFile) {
                await detectFromFile(currentFile);
            } else if (url) {
                await detectFromUrl(url);
            } else {
                alert('请先上传图片或输入图片URL');
            }
        });
        
        // 从文件检测
        async function detectFromFile(file) {
            const formData = new FormData();
            formData.append('file', file);
            
            const minFaceSize = document.getElementById('minFaceSize').value;
            const maxAngle = document.getElementById('maxAngle').value;
            const blurThreshold = document.getElementById('blurThreshold').value;
            
            if (minFaceSize) formData.append('min_face_size', minFaceSize);
            if (maxAngle) formData.append('max_angle', maxAngle);
            if (blurThreshold) formData.append('blur_threshold', blurThreshold);
            
            await performDetection('/detect', formData);
        }
        
        // 从URL检测
        async function detectFromUrl(url) {
            const formData = new FormData();
            formData.append('url', url);
            
            const minFaceSize = document.getElementById('minFaceSize').value;
            const maxAngle = document.getElementById('maxAngle').value;
            const blurThreshold = document.getElementById('blurThreshold').value;
            
            if (minFaceSize) formData.append('min_face_size', minFaceSize);
            if (maxAngle) formData.append('max_angle', maxAngle);
            if (blurThreshold) formData.append('blur_threshold', blurThreshold);
            
            // 预览URL图片
            previewContainer.innerHTML = `
                <img src="${url}" class="preview-image" alt="预览" onerror="this.src='data:image/svg+xml,<svg xmlns=%22http://www.w3.org/2000/svg%22 width=%22400%22 height=%22300%22><text x=%2250%%22 y=%2250%%22 text-anchor=%22middle%22>图片加载失败</text></svg>'">
            `;
            
            await performDetection('/detect/url', formData);
        }
        
        // 执行检测
        async function performDetection(endpoint, formData) {
            detectBtn.disabled = true;
            spinner.style.display = 'block';
            resultBox.style.display = 'none';
            
            try {
                const response = await fetch(endpoint, {
                    method: 'POST',
                    body: formData
                });
                
                const result = await response.json();
                displayResult(result);
                
            } catch (error) {
                displayResult({
                    success: false,
                    message: `请求失败: ${error.message}`,
                    data: null
                });
            } finally {
                detectBtn.disabled = false;
                spinner.style.display = 'none';
            }
        }
        
        // 显示结果
        function displayResult(result) {
            resultBox.style.display = 'block';
            
            if (result.success) {
                resultBox.className = 'result success';
                resultTitle.textContent = '✅ ' + result.message;
                
                if (result.data) {
                    const data = result.data;
                    let html = '<div class="stats-grid">';
                    
                    if (data.quality_score !== undefined) {
                        html += `
                            <div class="stat-item">
                                <div class="stat-label">质量评分</div>
                                <div class="stat-value">${(data.quality_score * 100).toFixed(1)}%</div>
                            </div>
                        `;
                    }
                    
                    if (data.blur_score !== undefined) {
                        html += `
                            <div class="stat-item">
                                <div class="stat-label">清晰度</div>
                                <div class="stat-value">${data.blur_score.toFixed(1)}</div>
                            </div>
                        `;
                    }
                    
                    if (data.face_size) {
                        html += `
                            <div class="stat-item">
                                <div class="stat-label">人脸尺寸</div>
                                <div class="stat-value">${data.face_size.width}×${data.face_size.height}</div>
                            </div>
                        `;
                    }
                    
                    if (data.pose) {
                        html += `
                            <div class="stat-item">
                                <div class="stat-label">姿态角度</div>
                                <div class="stat-value" style="font-size: 12px;">
                                    Y:${data.pose.yaw.toFixed(1)}° 
                                    P:${data.pose.pitch.toFixed(1)}° 
                                    R:${data.pose.roll.toFixed(1)}°
                                </div>
                            </div>
                        `;
                    }
                    
                    html += '</div>';
                    
                    if (data.age !== null && data.gender !== null) {
                        html += `<p style="margin-top: 15px; text-align: center;">
                            <span class="badge badge-info">年龄: ${data.age}</span>
                            <span class="badge badge-info">性别: ${data.gender === 1 ? '男' : '女'}</span>
                        </p>`;
                    }
                    
                    resultMessage.innerHTML = html;
                    resultDetails.style.display = 'block';
                    resultJson.textContent = JSON.stringify(result.data, null, 2);
                }
                
            } else {
                resultBox.className = 'result error';
                resultTitle.textContent = '❌ ' + result.message;
                resultMessage.innerHTML = result.data 
                    ? `<p>详细信息：${JSON.stringify(result.data)}</p>`
                    : '';
                resultDetails.style.display = result.data ? 'block' : 'none';
                if (result.data) {
                    resultJson.textContent = JSON.stringify(result.data, null, 2);
                }
            }
        }
        
        // 加载配置
        async function loadConfig() {
            try {
                const response = await fetch('/config');
                const config = await response.json();
                
                document.getElementById('minFaceSize').value = config.min_face_size;
                document.getElementById('maxAngle').value = config.max_angle;
                document.getElementById('blurThreshold').value = config.blur_threshold;
            } catch (error) {
                console.error('加载配置失败:', error);
            }
        }
        
        // 页面加载时加载配置
        loadConfig();
    </script>
</body>
</html>

